<template>
  <view class="container tn-safe-area-inset-bottom">
    <!-- 导航栏 -->
    <tn-nav-bar fixed alpha>
      <view slot="right" class="header-actions">
        <text class="tn-icon-more" @click="showMoreOptions"></text>
        <text class="tn-icon-target" @click="goToMap"></text>
      </view>
    </tn-nav-bar>
    
    <!-- 顶部标题区域 -->
    <view class="header-section">
      <view class="page-title">组织</view>
    </view>
    
    <!-- 标签导航 -->
    <view class="tabs-container">
      <scroll-view class="tabs-scroll" scroll-x :scroll-left="scrollLeft" :show-scrollbar="false">
        <view class="tabs-wrapper">
          <view 
            class="tab-item" 
            v-for="(tab, index) in tabs" 
            :key="index"
            :class="{ active: currentTab === index }"
            @click="switchTab(index)"
          >
            {{ tab }}
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-container">
        <text class="tn-icon-search search-icon"></text>
        <input 
          class="search-input" 
          type="text" 
          placeholder="搜索校友组织"
          v-model="searchKeyword"
          @input="onSearchInput"
        />
        <view class="search-btn" @click="handleSearch">
          搜索
        </view>
      </view>
    </view>
    
    <!-- 组织列表 -->
    <view class="content-section">
      <scroll-view class="list-scroll" scroll-y @scrolltolower="loadMore" :refresher-enabled="true" @refresherrefresh="onRefresh" :refresher-triggered="refreshing">
        <view 
          class="org-item" 
          v-for="(org, index) in organizationList" 
          :key="index"
          @click="goToOrgDetail(org)"
        >
          <view class="org-logo">
            <view class="logo-circle">
              <view class="logo-content">
                <text class="logo-text">JLASTU</text>
                <text class="logo-year">1907</text>
              </view>
            </view>
          </view>
          <view class="org-info">
            <view class="org-name">{{ org.name }}</view>
            <view class="org-stats">
              活动: {{ org.activityCount }} 成员: {{ org.memberCount }}
            </view>
            <view class="org-rating">
              <text class="rating-label">活跃度:</text>
              <view class="stars">
                <text 
                  class="star-icon" 
                  v-for="(star, starIndex) in 5" 
                  :key="starIndex"
                  :class="{ filled: starIndex < org.rating }"
                >★</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多提示 -->
        <view class="load-more" v-if="loading">
          <text>加载中...</text>
        </view>
        <view class="load-more" v-if="!hasMore && organizationList.length > 0">
          <text>没有更多了</text>
        </view>
        <view class="empty-state" v-if="!loading && organizationList.length === 0">
          <text class="empty-text">暂无组织</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 浮动操作按钮 -->
    <view class="fab" @click="goToCreateOrg">
      <text class="fab-icon">+</text>
    </view>
    
    <!-- 底部导航栏占位 -->
    <view class='tn-tabbar-height'></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabs: ['全部', '校友总会', '地方分会'],
      currentTab: 0,
      scrollLeft: 0,
      searchKeyword: '',
      refreshing: false,
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10,
      organizationList: [],
      allOrganizations: [] // 存储所有组织数据
    }
  },
  
  onLoad() {
    this.initAllOrganizations();
    this.loadOrganizations();
  },
  
  methods: {
    // 初始化所有组织数据
    initAllOrganizations() {
      // TODO: 从API获取所有组织数据
      this.allOrganizations = [
        {
          id: 1,
          name: '长春市校友会',
          type: '地方分会', // 组织类型：校友总会、地方分会
          activityCount: 3,
          memberCount: 501,
          rating: 5
        },
        {
          id: 2,
          name: '贵州省校友会',
          type: '地方分会',
          activityCount: 0,
          memberCount: 53,
          rating: 5
        },
        {
          id: 3,
          name: '校友工作志愿者协会',
          type: '校友总会',
          activityCount: 3,
          memberCount: 192,
          rating: 5
        },
        {
          id: 4,
          name: '吉林市校友会',
          type: '地方分会',
          activityCount: 2,
          memberCount: 432,
          rating: 5
        },
        {
          id: 5,
          name: '辽宁省分会',
          type: '地方分会',
          activityCount: 0,
          memberCount: 117,
          rating: 5
        },
        {
          id: 6,
          name: '北京校友总会',
          type: '校友总会',
          activityCount: 5,
          memberCount: 1200,
          rating: 5
        },
        {
          id: 7,
          name: '上海校友会',
          type: '地方分会',
          activityCount: 4,
          memberCount: 856,
          rating: 5
        },
        {
          id: 8,
          name: '广州校友会',
          type: '地方分会',
          activityCount: 2,
          memberCount: 623,
          rating: 4
        },
        {
          id: 9,
          name: '深圳校友会',
          type: '地方分会',
          activityCount: 3,
          memberCount: 789,
          rating: 5
        },
        {
          id: 10,
          name: '全国校友总会',
          type: '校友总会',
          activityCount: 6,
          memberCount: 5000,
          rating: 5
        }
      ];
    },
    
    // 切换标签
    switchTab(index) {
      if (this.currentTab === index) return;
      this.currentTab = index;
      this.page = 1;
      this.hasMore = true;
      this.organizationList = [];
      this.filterAndLoadOrganizations();
    },
    
    // 搜索输入
    onSearchInput(e) {
      this.searchKeyword = e.detail.value;
    },
    
    // 执行搜索
    handleSearch() {
      this.page = 1;
      this.hasMore = true;
      this.organizationList = [];
      this.filterAndLoadOrganizations();
    },
    
    // 筛选并加载组织列表
    filterAndLoadOrganizations() {
      if (this.loading) return;
      
      this.loading = true;
      
      // 模拟API延迟
      setTimeout(() => {
        // 根据标签和搜索关键词筛选
        let filteredList = this.filterOrganizations();
        
        // 分页处理
        const startIndex = (this.page - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageData = filteredList.slice(startIndex, endIndex);
        
        if (this.page === 1) {
          this.organizationList = pageData;
        } else {
          this.organizationList = this.organizationList.concat(pageData);
        }
        
        // 判断是否还有更多数据
        this.hasMore = endIndex < filteredList.length;
        
        this.page++;
        this.loading = false;
        this.refreshing = false;
      }, 500);
    },
    
    // 筛选组织数据
    filterOrganizations() {
      let filtered = [...this.allOrganizations];
      
      // 根据标签筛选
      if (this.currentTab > 0) {
        const selectedType = this.tabs[this.currentTab];
        filtered = filtered.filter(org => org.type === selectedType);
      }
      
      // 根据搜索关键词筛选
      if (this.searchKeyword && this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase();
        filtered = filtered.filter(org => 
          org.name.toLowerCase().includes(keyword)
        );
      }
      
      return filtered;
    },
    
    // 加载组织列表（兼容旧方法，用于下拉刷新等）
    loadOrganizations() {
      this.filterAndLoadOrganizations();
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.hasMore = true;
      this.organizationList = [];
      this.filterAndLoadOrganizations();
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadOrganizations();
      }
    },
    
    // 跳转到组织详情
    goToOrgDetail(org) {
      uni.navigateTo({
        url: `/pages/orgDetail?id=${org.id}`
      });
    },
    
    // 跳转到创建组织页
    goToCreateOrg() {
      uni.navigateTo({
        url: '/minePages/organization_create' // 根据实际路由路径调整
      });
    },
    
    // 显示更多选项
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['筛选', '排序', '刷新'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.showFilter();
          } else if (res.tapIndex === 1) {
            this.showSort();
          } else if (res.tapIndex === 2) {
            this.onRefresh();
          }
        }
      });
    },
    
    // 前往地图
    goToMap() {
      uni.navigateTo({
        url: '/pages/orgMap'
      });
    },
    
    // 显示筛选
    showFilter() {
      uni.showToast({
        title: '筛选功能开发中',
        icon: 'none'
      });
    },
    
    // 显示排序
    showSort() {
      uni.showActionSheet({
        itemList: ['按活跃度', '按成员数', '按活动数'],
        success: (res) => {
          // TODO: 实现排序逻辑
          uni.showToast({
            title: '排序功能开发中',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
// 主容器样式
.container {
  background-color: #ffffff;
  min-height: 100vh;
}

// 导航栏样式
.header-actions {
  display: flex;
  gap: 20rpx;
  padding-right: 20rpx;
  
  text {
    font-size: 36rpx;
    color: #FFFFFF;
    padding: 10rpx;
  }
}

// 顶部标题区域
.header-section {
  padding: 120rpx 40rpx 30rpx;
  background-color: #ffffff;
}

.page-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333333;
}

// 标签导航样式
.tabs-container {
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.tabs-scroll {
  white-space: nowrap;
  width: 100%;
}

.tabs-wrapper {
  display: flex;
  padding: 0 20rpx;
}

.tab-item {
  display: inline-block;
  padding: 24rpx 32rpx;
  font-size: 28rpx;
  color: #666666;
  white-space: nowrap;
  position: relative;
  transition: color 0.3s;
  
  &.active {
    color: #2E86AB;
    font-weight: 500;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 32rpx;
      right: 32rpx;
      height: 4rpx;
      background-color: #2E86AB;
      border-radius: 2rpx;
    }
  }
}

// 搜索栏样式
.search-section {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
}

.search-container {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 50rpx;
  padding: 0 24rpx;
  height: 72rpx;
}

.search-icon {
  font-size: 32rpx;
  color: #999999;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  height: 72rpx;
  line-height: 72rpx;
}

.search-btn {
  padding: 12rpx 24rpx;
  background-color: #1F4D4B;
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 26rpx;
  margin-left: 16rpx;
}

// 内容区域
.content-section {
  flex: 1;
  padding: 20rpx 30rpx;
  padding-bottom: 200rpx;
}

.list-scroll {
  height: calc(100vh - 420rpx);
}

// 组织列表项样式
.org-item {
  display: flex;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.1);
  }
}

.org-logo {
  width: 120rpx;
  height: 120rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-circle {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #2E86AB 0%, #1F4D4B 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40%;
    background-color: rgba(255, 255, 255, 0.1);
  }
}

.logo-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.logo-text {
  font-size: 20rpx;
  color: #ffffff;
  font-weight: bold;
  letter-spacing: 1rpx;
  margin-bottom: 4rpx;
}

.logo-year {
  font-size: 18rpx;
  color: #ffffff;
  font-weight: 500;
}

.org-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.org-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 12rpx;
}

.org-stats {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 12rpx;
}

.org-rating {
  display: flex;
  align-items: center;
}

.rating-label {
  font-size: 24rpx;
  color: #999999;
  margin-right: 8rpx;
}

.stars {
  display: flex;
  gap: 4rpx;
}

.star-icon {
  font-size: 28rpx;
  color: #e0e0e0;
  
  &.filled {
    color: #FFD700;
  }
}

// 加载更多和空状态
.load-more {
  text-align: center;
  padding: 40rpx 0;
  font-size: 26rpx;
  color: #999999;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

// 浮动操作按钮
.fab {
  position: fixed;
  right: 30rpx;
  bottom: 180rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #1F4D4B;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(31, 77, 75, 0.3);
  z-index: 99;
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 8rpx rgba(31, 77, 75, 0.3);
  }
}

.fab-icon {
  font-size: 60rpx;
  color: #ffffff;
  font-weight: 300;
  line-height: 1;
}

// 底部占位
.tn-tabbar-height {
  min-height: 120rpx;
  height: calc(140rpx + env(safe-area-inset-bottom));
}
</style>